//
//  YMSHomeController.swift
//  YMSWeibo
//
//  Created by 杨茂盛 on 2016/11/12.
//  Copyright © 2016年 杨茂盛. All rights reserved.
//

import UIKit
import SVProgressHUD

//由于要多次计算行高 会用到cell的tabbar 但是只要有一个cell就够了 不许要多次创建
let orginalCell = UINib(nibName: "YMSStatusCell", bundle: nil).instantiate(withOwner: nil, options: nil).last as! YMSStatusCell
let reweentedCell = UINib(nibName: "YMSRetweetedStatuseCell", bundle: nil).instantiate(withOwner: nil, options: nil).last as! YMSStatusCell

private let originalCellId = "YMSStatusCell"
private let retweetedCellId = "YMSRetweenCell"



class YMSHomeController: YMSBaseTableController {
    
    lazy var needLoadArray: [IndexPath] = [IndexPath]()//存储作为判断要加载数组的数量
    
    //处理视图的viewModel
    lazy var homeViewModel:YMSHomeViewModel = YMSHomeViewModel()

    //自定义的下拉刷新控件
    lazy var ymsRefreshControl:YMSRefreshControl = YMSRefreshControl()
    
    var count = 0 //用来返回cell的行高
    
    
    //cell的ID
   let YMSStatusCell = "YMSStatusCell"
    let YMSRetweenCell = "YMSRetweenCell"

    //属性,记录一下获取到的信息 ：数组
    lazy var dataArray:[YMSStatuses] = [YMSStatuses]()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(clickBtn))

        if !userLogin {
            //用户没有登录
            myView.setInFo(title: "我胡汉三二十年后又是一条好汉,我胡汉三二十年后又是一条好汉", imageName: "visitordiscover_feed_image_smallicon", isHome:  YMSUserinfoViewModel.shared.userLogin)
            return
        }

        //MARK: 注册cell
        let nib :UINib = UINib(nibName: "YMSStatusCell", bundle: nil)
        
        self.tableView.register(nib, forCellReuseIdentifier: YMSStatusCell)
        //注册转发微博的cell
        let nibRetweenNib = UINib(nibName: "YMSRetweetedStatuseCell", bundle: nil)
        self.tableView.register(nibRetweenNib, forCellReuseIdentifier: YMSRetweenCell)
        //去掉tableview的分隔线
        tableView.separatorStyle = .none
        //将小菊花添作为tableview的footView
        tableView.tableFooterView = indicatorView
        //下拉小菊花
//        refreshControl = UIRefreshControl() //直接实例化
//        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
        //用自定义的下拉
        ymsRefreshControl.addTarget(self, action: #selector(loadData), for: .valueChanged)
        self.view .addSubview(ymsRefreshControl)
        
        //MARK: 设置显示刷新Label 
        tipLabel.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 35)
        //设置y值
        tipLabel.frame.origin.y = 64-35
        //移动到导航条下面
        self.navigationController?.view.insertSubview(tipLabel, belowSubview: self.navigationController!.navigationBar)
        
        
        //进入界面之后就加载数据
        loadData()
    }
    
 @objc private func loadData(){
        homeViewModel.loadData(isPull: indicatorView.isAnimating) { (isSuccess,count) in
            if !isSuccess{
                return
            }
//MARK: 问题1
            if !self.indicatorView.isAnimating{
            self.startAnimation(count: count)
            }
            
            //需要菊花停止转动,否则只能加载两次数据 初次和第二次
            self.indicatorView.stopAnimating()
            //self.refreshControl?.endRefreshing()
            
            self.ymsRefreshControl.endRefreshing()
            self.startAnimation(count: count)
            self.tableView.reloadData()
        }
    }
    
    //提示显示有多少条数据
    func startAnimation(count:Int){
        if tipLabel.isHidden == false {
            return
        }
        let tipText = count == 0 ? "没有新微博":"有\(count)条微博"
           tipLabel.text = tipText
        //开始就显示
        self.tipLabel.isHidden = false
        //在开始动画之前记录Y值
        let y = self.tipLabel.frame.origin.y
        UIView.animate(withDuration: 1, animations: {
            //2. 做动画 修改Y值
            self.tipLabel.frame.origin.y = 64
        }, completion:{ (_) -> () in
            //3. 回去的动画  延迟
            UIView.animate(withDuration: 1, delay: 1, options: [], animations: {
                self.tipLabel.frame.origin.y = y
            }, completion: { (_) -> () in
                self.tipLabel.isHidden = true
            })
        })
    }

    //实例化提示加载数据的UILable控件
    var tipLabel :UILabel = {
        let myLabel = UILabel()
        myLabel.text = ""
        myLabel.font = UIFont.systemFont(ofSize: 14)
        myLabel.textColor = #colorLiteral(red: 0.9411764741, green: 0.4980392158, blue: 0.3529411852, alpha: 1)
        myLabel.backgroundColor =  #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
        myLabel.isHidden = true
        myLabel.textAlignment = .center
        return myLabel
    }()
    
    
    //MARK: 按钮点击事件
    @objc private func clickBtn(){
        self.navigationController?.pushViewController(YMSModalController(), animated: true)
    }
    //懒加载小菊花
   internal lazy var indicatorView:UIActivityIndicatorView = {
    let indicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        //indicator.startAnimating()
        return indicator
    }()

//--------------------------tableview的数据源方法---------------------------------
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.homeViewModel.viewModelArray.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         let cellViewModel = self.homeViewModel.viewModelArray[indexPath.row]
        
        //根据viewModel来判断使用哪一个可重用标识符
        let cellIdentifier = getCellId(viewmodel: cellViewModel)
        
        //通过是否转发微博来确认cell的identifier
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
            as! YMSStatusCell
    
        //如果需要加载的数组的数量大于0 并且要加载的indexPath不在按需加载的数组中,就不渲染cell
        
        if needLoadArray.count > 0 {
            let result = needLoadArray.contains(where: { (index) -> Bool in
                
                return index.row == indexPath.row && index.section == indexPath.section
            })
            
            if !result {
                //print("^    😈😈😈😈😈😈😈打酱油😈😈😈😈😈😈")
                return cell
            }
        }

        cell.viewModel = cellViewModel
        return cell
    }
    
    //处理cell快速滑动造成卡顿
    override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        guard let ip = tableView.indexPathForRow(at: CGPoint(x: 0, y: targetContentOffset.pointee.y)) else {
            return
        }
        guard let cip = tableView.indexPathsForVisibleRows?.first else {
            return
        }
        
        let skipCount = 12;
        
        if labs(cip.row - ip.row) > skipCount {
            guard let temp = tableView.indexPathsForRows(in: CGRect(x: 0, y: targetContentOffset.pointee.y, width: self.view.frame.width, height: self.view.frame.height)) else {
                
                return
            }
            var arr = temp
            print(velocity.y)
            //向下滑动
            if velocity.y < 0 {
                
                let indexPath = temp.last!
                if (indexPath.row + 3 < self.homeViewModel.viewModelArray.count) {
                    arr.append(IndexPath(row: indexPath.row + 1, section: 0))
                    arr.append(IndexPath(row: indexPath.row + 2, section: 0))
                    arr.append(IndexPath(row: indexPath.row + 3, section: 0))
                }
            }else{
                //向上滑动
                let indexPath = temp.first!
                if (indexPath.row > 3) {
                    arr.append(IndexPath(row: indexPath.row - 3, section: 0))
                    arr.append(IndexPath(row: indexPath.row - 2, section: 0))
                    arr.append(IndexPath(row: indexPath.row - 1, section: 0))
                }
            }
            needLoadArray.append(contentsOf: arr)
        }
    }
    
    //修改自动行高
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        //获取cell
        
        count = count + 1
        
        let viewModel = self.homeViewModel.viewModelArray[indexPath.row]
        
        
        //获取一个不用显示的cell来完成自动行高计算
        
       // let cell = self.loadCell(viewmodel: viewModel)
//        cell.viewModel = viewModel
//        cell.layoutIfNeeded()
        return viewModel.rowHeight
        

    }
    
    override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        //print("------------------scrollViewWillBeginDragging")
        needLoadArray.removeAll()
    }
    
    override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
       // print("------------------scrollViewWillBeginDragging")
        needLoadArray.removeAll()
    }

    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indicatorView.isAnimating == false && indexPath.row == homeViewModel.viewModelArray.count - 2 {
            indicatorView.startAnimating()
            print("小菊花开始转啦")
            self.loadData()
        }
    }
    
    
    //载入一个cell
    private func loadCell(viewmodel:YMSStatusesViewModel) -> YMSStatusCell{
        //根据外界传来的一个视图模型,返回一个cell
        return (viewmodel.status?.retweeted_status == nil) ? orginalCell:reweentedCell
    }
    //根据数据获取可重用标识符
    
    private func getCellId(viewmodel:YMSStatusesViewModel) -> String
    {
    //根据外界传来的一个视图模型,来返回一个字符串 cellid
        return viewmodel.status?.retweeted_status == nil ? originalCellId:retweetedCellId
    }
}
